package com.simulation.config;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxn
 * @date 2022/12/4  11:18
 */
@Configuration
public class EventBusConfig {
    /**
     * 不管是否空闲 都会有n条线程存活
     */
    private static final int ALWAYS_ALIVE = 6;
    private static final int MAX_THREAD_SIZE = 12;
    private static final long KEEP_ALIVE_TIME = 60L;
    private static final int BLOCKING_QUEUE_SIZE = 2048;

    @Bean
    public AsyncEventBus asyncEventBus() {
        // 核心线程6个
        // 最大线程12个
        // 线程空闲后存活时间 60秒
        // 最多放入队列2048 没有资源是直接抛出异常
        return new AsyncEventBus(new ThreadPoolExecutor(ALWAYS_ALIVE, MAX_THREAD_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
                new LinkedBlockingQueue(BLOCKING_QUEUE_SIZE), new ThreadFactoryBuilder().setNameFormat("asyncEventbus-pool-%d").build()
                , new ThreadPoolExecutor.AbortPolicy()));
    }

    @Bean
    public EventBus eventBus(){
        return new EventBus("eventBus-pool");
    }
}
